/**
 * @计算一个数的平方根,并察看平方根变化
 *
 * @author	 wangshikun <wangshikun2010@gmail.com>
 * @copyright	(c) 2012 wangshikun <wangshikun2010@gmail.com>
 * @license	http://www.opensource.org/licenses/mit-license.php The MIT License
 * @package	default
 * @subpackage	default
 */

#include <stdio.h>
#include <cs50.h>

float absoluteValue(float x);
double squareRoot(double x);

int main(int argc, char *argv[]) {

	printf("please enter a number: ");
	double x = GetFloat();

	printf("squareRoot(%f) = %f\n", x, squareRoot(x));

	return 0;
}

float absoluteValue(float x) {
	if (x < 0) {
		x = -x;
	} 

	return x;
}

//处理平方根
double squareRoot(double x) {
	const float epsilon = 0.00001;
	float guess = 1.0;
	int i = 0;

	double value = x;

	if (x < 0) {
		printf("sorry, number entered is out of range!\n");
		return -1;
	} else if (x == 0){
		return x;
	} else {

		//找到平方根的过程，并计算找到平方根用的次数
		while (absoluteValue(guess * guess - x) >= epsilon) {
			guess = (x / guess + guess) / 2;
			printf("guess=%f\n", guess);
			i++;
		}
		printf("用了%d次找到%f的平方根\n", i, value);
	}

	return guess;
}

